package syntelos.sx;

import alto.lang.Date;
import alto.lang.Message;
import alto.lang.Status;

/**
 * 
 */
public class LogRR
    extends syntelos.lang.Message.Queue
{
    public final static int AVG_NUMBER = 40;

    protected final Request request;
    protected final Response response;

    public LogRR(Message.Queue queue, Request request, Response response){
        super(queue,request.getReferenceLog());
        if (null != request){
            this.request = request;
            this.response = response;
        }
        else
            throw new IllegalArgumentException();
    }

    protected final void formatRRHead()
        throws java.io.IOException
    {
        Request request = this.request;
        Response response = this.response;

        String elapsedMs = "", txLength="";
        if (null != response){

            elapsedMs = response.getTimeElapsedMillis();

            txLength = String.valueOf(response.getTransactionLength(request));
        }

        String clientaddr; 

        java.net.InetAddress addr = request.getClientAddress();
        if (null != addr)
            clientaddr = SafeEmpty(addr.getHostAddress());
        else
            clientaddr = "";


        String clientident;

        java.security.Principal ident = request.getPrincipal();
        if (null != ident)
            clientident = SafeEmpty(ident.getName());
        else
            clientident = "";

        this.println("<log type=\"http\" client-addr=\""+clientaddr+"\" client-user=\""+clientident+"\" tx-length=\""+txLength+"\" tx-elapsed-ms=\""+elapsedMs+"\">");

    }
    protected final void formatRRTail()
        throws java.io.IOException
    {
        Request request = this.request;
        Response response = this.response;
        this.println(" <request content=\"head\" type=\"message/http\"><![CDATA[");
        this.write(request.getTrace());
        this.println("]]></request>");
        this.println(" <response content=\"head\" type=\"message/http\"><![CDATA[");
        if (null != response)
            this.write(response.getTrace());
        this.println("]]></response>");
        this.println("</log>");
    }
    public void formatMessage()
        throws java.io.IOException
    {
        this.resetall();
        this.formatRRHead();
        this.formatRRTail();
    }
}
